package com.xiaoge.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoge.converter.MenuConverter;
import com.xiaoge.entity.Menu;
import com.xiaoge.exception.BusinessException;
import com.xiaoge.mapper.MenuMapper;
import com.xiaoge.service.MenuService;
import com.xiaoge.utils.MenuTreeBuilder;
import com.xiaoge.vo.MenuNodeVO;
import com.xiaoge.vo.MenuVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author XiaoGe
 * @since 2022-05-28
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    /**
     * 加载菜单树（按钮和菜单）
     *
     * @return
     */
    @Override
    public List<MenuNodeVO> findMenuTree() {
        //查询所有的菜单列表
        List<Menu> menus = menuMapper.selectList(null);
        List<MenuNodeVO> menuNodeVOS = MenuConverter.converterToALLMenuNodeVO(menus);
        //通过工具类去构建一个树形对象
        return MenuTreeBuilder.build(menuNodeVOS);
    }

    @Override
    public List<Long> findOpenIds() {
        List<Long> ids=new ArrayList<>();
        List<Menu> menus = menuMapper.selectList(null);
        if(!CollectionUtils.isEmpty(menus)){
            for (Menu menu : menus) {
                if(menu.getOpen()==1){
                    ids.add(menu.getId());
                }
            }
        }
        return ids;
    }

    @Override
    public MenuVO edit(Long id) {
        Menu menu = menuMapper.selectById(id);
        if(menu==null){
            throw new BusinessException("该编辑的菜单不存在");
        }
        return MenuConverter.converterToMenuVO(menu);
    }

    @Override
    public void updateMenu(MenuVO menuVO) {
        Menu dbMenu = menuMapper.selectById(menuVO.getId());
        if(dbMenu==null){
            throw new BusinessException("要更新的菜单不存在");
        }
        Menu menu = new Menu();
        BeanUtils.copyProperties(menuVO,menu);
        menu.setId(menuVO.getId());
        menu.setAvailable(menuVO.isDisabled()?0:1);
        menu.setModifiedTime(new Date());
        menuMapper.updateById(menu);
    }

    @Override
    public void delete(Long id) {
        Menu menu = menuMapper.selectById(id);
        if(menu==null){
            throw new BusinessException("要删除的菜单不存在");
        }
        menuMapper.deleteById(id);
    }

    @Override
    public Menu add(MenuVO menuVO) {
        Menu menu = new Menu();
        BeanUtils.copyProperties(menuVO,menu);
        menu.setCreateTime(new Date());
        menu.setModifiedTime(new Date());
        menu.setAvailable(menuVO.isDisabled()?0:1);
        menuMapper.insert(menu);
        return menu;
    }
}
